package com.haitaoit.chengquan.module.center.activity.xuqiu;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ImageAdapter;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetPhotoListener;
import com.haitaoit.chengquan.utils.GetPhotoOrImage;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.QRatingBar;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class XuqiuEvaluateActivity extends BaseActivity {
    @ViewInject(R.id.eva_star)
    QRatingBar      eva_star;
    @ViewInject(R.id.eva_content)
    TextView        eva_content;
    @ViewInject(R.id.image)
    CircleImageView image;
    @ViewInject(R.id.add_eva_img)
    MyGridView      add_eva_img;


    private ImageAdapter adapter;
    private GetPhotoOrImage getPhotoOrImage;
    private int change = 0;
    private String demand_id, type;
    private String mImage_uri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_xuqiu_evaluate);
        setTitle_V("评价");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        demand_id = getIntent().getStringExtra("demand_id");
        type = getIntent().getStringExtra("type");
        mImage_uri = getIntent().getStringExtra("circleimage_uri");

        adapter = new ImageAdapter(this);
        adapter.setBackCall(backCall);
        add_eva_img.setAdapter(adapter);
        getPhotoOrImage = new GetPhotoOrImage(this);


        Glide.with(this).load(mImage_uri).error(R.mipmap.ic_launcher).into(image);

    }

    @OnClick({R.id.eva_add,})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.eva_add:
                if (eva_content.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入评价内容！");
                } else {
                    if (type.equals("1")) {
                        httpadd_demand_evaluation();
                    } else if (type.equals("2")) {
                        httpadd_mer_demand_evaluation();
                    }
                }
                break;
        }
        super.onClick(v);
    }

    // 需求商 发布评价
    private void httpadd_demand_evaluation() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("content", eva_content.getText().toString()));
        list.add(new NameValuePairSign("demand_id", demand_id));
        list.add(new NameValuePairSign("score", ((int) eva_star.getRating()) + ""));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_demand_evaluation + "user_id=" +
                PreferenceUtils.getPrefString("user_id", "") + "&content=" + eva_content.getText().toString()
                + "&demand_id=" + demand_id + "&score=" + ((int) eva_star.getRating()) + "&sign=" + sign;
        JSONObject params = new JSONObject();
        try {
            JSONArray house_imgs = new JSONArray();
            for (int i = 0; i < adapter.getList().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("img_url", adapter.getList().get(i).getImg());
                house_imgs.put(jsonObject);
            }
            params.put("img", house_imgs);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, true, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 服务商 发布评价
    private void httpadd_mer_demand_evaluation() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("content", eva_content.getText().toString()));
        list.add(new NameValuePairSign("demand_offer_id", demand_id));
        list.add(new NameValuePairSign("score", ((int) eva_star.getRating()) + ""));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_mer_demand_evaluation + "user_id=" +
                PreferenceUtils.getPrefString("user_id", "") + "&content=" + eva_content.getText().toString()
                + "&demand_offer_id=" + demand_id + "&score=" + ((int) eva_star.getRating()) + "&sign=" + sign;
        JSONObject params = new JSONObject();
        try {
            JSONArray house_imgs = new JSONArray();
            for (int i = 0; i < adapter.getList().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("img_url", adapter.getList().get(i).getImg());
                house_imgs.put(jsonObject);
            }
            params.put("img", house_imgs);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, true, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.icon:
                    if (position == adapter.getList().size()) {
                        getPhotoOrImage.setGetPhotoListener(getPhoto1);
                        getPhotoOrImage.getImage();
                    } else {
                        Dialog dlg = DialogUtil.ShowTop(XuqiuEvaluateActivity.this, new BackCall() {
                            @Override
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.tv_photos:// 图库
                                        getPhotoOrImage.setGetPhotoListener(getPhoto);
                                        getPhotoOrImage.getImage();
                                        break;
                                    case R.id.tv_camera:
                                        List<Img> list = adapter.getList();
                                        list.remove(change);
                                        adapter.setList(list);
                                        adapter.notifyDataSetChanged();
                                        break;
                                }
                                super.deal(which, obj);
                            }
                        });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        XuqiuEvaluateActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getPhotoOrImage.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.set(change, img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto1 = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.add(img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };
}
